import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';

/// State 基类
class BMFBaseMapState<T extends StatefulWidget> extends State<T> {
  BMFMapController myMapController;
  BMFCoordinate centerBMFCoordinate = BMFCoordinate(31.185044, 121.584797);
  Size screenSize;

  /// 定位模式
  // BMFUserTrackingMode _userTrackingMode = BMFUserTrackingMode.Follow;
  // Map<String, Object> _loationResult;

  /// 我的位置
  BMFUserLocation _userLocation;
  StreamSubscription<Map<String, Object>> locationListener;
  BaiduLocation baiduLocation; // 定位结果
  LocationFlutterPlugin locationPlugin = new LocationFlutterPlugin();

  @override
  void initState() {
    super.initState();

    /// 动态申请定位权限
    locationPlugin.requestPermission();
    LocationFlutterPlugin.setApiKey("xolHL3nn4nECYeE9W2HLFx0Kaito4ae6");

    /// 动态监听地图信息
    locationListener =
        locationPlugin.onResultCallback().listen((Map<String, Object> result) {
      // setState(() {
      // print('更新了状态');
      if (result != null) {
        //loationResult = result;
        try {
          // 将原生端返回的定位结果信息存储在定位结果类中
          baiduLocation = BaiduLocation.fromMap(result);
          print("baiduLocation: ${baiduLocation?.getMap()}");
        } catch (e) {
          print(e);
        }
      }
      // });
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (null != locationListener) {
      // 停止定位
      locationListener?.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    startLocation();
    return MaterialApp(
      home: Scaffold(),
    );
  }

  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;

    /// 地图加载回调
    myMapController.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
    });
  }

  /// 设置地图参数
  BMFMapOptions initMapOptions() {
    BMFMapOptions mapOptions = BMFMapOptions(
      center: centerBMFCoordinate,
      zoomLevel: 18,
    );
    return mapOptions;
  }

  /// 创建地图
  Container generateMap() {
    locationPlugin.requestPermission();

    return Container(
      height: screenSize.height,
      width: screenSize.width,
      child: BMFMapWidget(
        onBMFMapCreated: onBMFMapCreated,
        mapOptions: initMapOptions(),
      ),
    );
  }

  /// 创建控制栏
  Widget generateControlBar() {
    throw UnimplementedError();
  }

  /// 启动定位
  void startLocation() {
    if (null != locationPlugin) {
      _setLocOption();
      locationPlugin.startLocation();
    }
  }

  /// 停止定位
  void stopLocation() {
    locationPlugin.stopLocation();
  }

  /// 更新位置
  void updateUserLocation() {
    BMFCoordinate coordinate =
        BMFCoordinate(baiduLocation.latitude, baiduLocation.longitude);
    BMFLocation location = BMFLocation(
        coordinate: coordinate,
        altitude: 0,
        horizontalAccuracy: 5,
        verticalAccuracy: -1.0,
        speed: -1.0,
        course: -1.0);
    BMFUserLocation userLocation = BMFUserLocation(location: location);
    _userLocation = userLocation;
    myMapController.updateLocationData(_userLocation);
  }

  /// 设置android端和ios端定位参数
  void _setLocOption() {
    /// android 端设置定位参数
    BaiduLocationAndroidOption androidOption = new BaiduLocationAndroidOption();
    androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(1000); // 设置发起定位请求时间间隔

    Map androidMap = androidOption.getMap();

    /// ios 端设置定位参数
    BaiduLocationIOSOption iosOption = new BaiduLocationIOSOption();
    iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    iosOption.setBMKLocationCoordinateType(
        "BMKLocationCoordinateTypeBMK09LL"); // 设置返回的位置坐标系类型
    iosOption.setActivityType("CLActivityTypeAutomotiveNavigation"); // 设置应用位置类型
    iosOption.setLocationTimeout(10); // 设置位置获取超时时间
    iosOption.setDesiredAccuracy("kCLLocationAccuracyBest"); // 设置预期精度参数
    iosOption.setReGeocodeTimeout(10); // 设置获取地址信息超时时间
    iosOption.setDistanceFilter(100); // 设置定位最小更新距离
    iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
    iosOption.setPauseLocUpdateAutomatically(true); //  定位是否会被系统自动暂停

    Map iosMap = iosOption.getMap();

    locationPlugin.prepareLoc(androidMap, iosMap);
  }
}
